<?php

/**
 * O2O团购PC版本
 * ============================================================================
 * * 版权所有 2009-2016 郑州司科计算机科技有限公司，并保留所有权利。
 * 购买网址: http://www.jzphp.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
  * 咨询电话：400-823-0371 QQ：313999875
 * ============================================================================
 * $Author: zzsike $
 * $Time 2016-02-03 sammy $
*/


require_once(dirname(dirname(__FILE__)) . '/app.php');
require_once(dirname(__FILE__) . '/paybank.php');

need_login();

if (is_post()) {
	$order_id = abs(intval($_POST['order_id']));
	$point=($_POST['point'])? (real)(trim($_POST['point'])) : 0;
	$money=($_POST['money'])? (real)(trim($_POST['money'])) : 0;
	$condition = array( 
			 "packageid = $order_id or id = $order_id",  
			);
	$order_list = DB::LimitQuery('order', array(
		'condition' => $condition,
	));
} else {
	if ( $_GET['id'] == 'charge' ) {
		redirect( WEB_ROOT. '/credit/index.php');
	}
	$order_id = $id = abs(intval($_GET['id']));
}

if(!$order_id || !($order = Table::Fetch('order', $order_id))) {
	redirect( WEB_ROOT. '/index.php');
}
if ( $order['user_id'] != $login_user['id']) {
	redirect( WEB_ROOT . "/team.php?id={$order['team_id']}");
}
if($_POST['origin'])
	$total_origin=$_POST['origin'];
else
	$total_origin=$order['origin'];

foreach($order_list as $k=>$v){
	$team = Table::Fetch('team', $v['team_id']);
	team_state($team);
}


if (is_post() && $_POST['paytype'] ) {
	$uarray = array( 'service' => pay_getservice($_POST['paytype']) );
	foreach($order_list as $k=>$v){
		Table::UpdateCache('order', $v['id'], $uarray);
	}
	
	$order = Table::Fetch('order', $order_id);
	$order['service'] = pay_getservice($_POST['paytype']);
}

$team_ids = Utility::GetColumn($order_lists, 'team_id');
$teams = Table::Fetch('team', $team_ids);

foreach($teams as $key=>$value){
	$team_id=$value['id'];
	if ( $_POST['paytype']!='credit' 
		&& $_POST['service']!='credit' 
		&& $value['team_type']=='seconds' 
		&& ($total_origin>$login_user['money'])
		&& option_yes('creditseconds')
	   ) {
		$need_money = ceil($total_origin - $login_user['money']);
		Session::Set('error', "秒杀项目仅可以使用余额付款，您的余额不足，还需要充值{$need_money}元才可以完成秒杀");
		redirect(WEB_ROOT . "/credit/charge.php?money={$need_money}");
	}
	
	//peruser buy count
	if ($_POST && $value['per_number']>0) {
		$now_count = Table::Count('order', array(
			'user_id' => $login_user_id,
			'team_id' => $value['id'],
			'state' => 'pay',
		), 'quantity');
		$leftnum = ($value['per_number'] - $now_count);
		
		if ($leftnum <= 0) {
			Session::Set('error', '您购买本单产品的数量已经达到上限，快去关注一下其他产品吧！');
			redirect( WEB_ROOT . "/team.php?id={$team_id}"); 
		}
	}
	
	/* noneed pay where goods soldout or end */
	if ($value['close_time']) {
		Session::Set('notice', '本单产品团购已结束，现在不能进行付款');
		redirect(WEB_ROOT  . "/team.php?id={$team_id}");
	}
	/* noneed pay where goods soldout or end */
	if ($value['now_number']>$value['maxnumber'] && $value['maxnumber']>0 ) {
		Session::Set('notice', '本单产品团购已卖光，现在不能进行付款');
		redirect(WEB_ROOT  . "/team.php?id={$team_id}");
	}
	/* end */


}


//payed order
if ( $order['state'] == 'pay' ) {  
	if ( is_get() ) {
          
		die(include template('order_pay_success'));		
	} else {
		redirect(WEB_ROOT  . "/order/pay.php?id={$order_id}");
	}
}

$total_money = moneyit($total_origin - $point-$money);

/*if ($total_money<=0) { 
	$total_money = 0; $order['service'] = 'credit'; 
}*/
if($point || $money){
	$score=$point;
	$credit =$money;
	foreach($order_list as $k=>$v){
		$ss=0;
		$cc=0;
		if($score>=0){
			if($score>=$v['origin']){
				$ss=$v['origin'];
				$score -=$v['origin'];
			}else{
				$ss=$score;
				$score=0;
				if($credit>0){
					$lm=$v['origin']-$ss;
					if($lm>0){
						if($credit>=$lm){
							$cc=$lm;
							$credit -=$lm;
						}else{
							$cc=$credit;
							$credit=0;
						}
					}
				}
			}
			$online_pay=(real)($v['origin']-$cc-$ss);
			//if ($order['credit']!=$cc) {
				Table::UpdateCache('order', $v['id'], array('point'=>$ss,'credit'=>$cc,'money'=>$online_pay));
			//}
		}
		
	}
	
}


/* generate unique pay_id 
检查订单的pay_id
付款订单必须有pay_id
*/
if (!($pay_id = $order['pay_id'])) {
	$randid = strtolower(Utility::GenSecret(4, Utility::CHAR_WORD));
	$pay_id = "go-{$order['id']}-{$order['quantity']}-{$randid}";
	Table::UpdateCache('order', $order['id'], array(
				'pay_id' => $pay_id,
				));
}


/* credit pay */
if ( $_POST['action'] == 'redirect' ) {
	redirect($_POST['reqUrl']);
}
elseif ( $_POST['paytype'] == 'credit' ) {
	if ( $total_origin >($money+$point) ){
		/*foreach($order_list as $k=>$v){  //选择用余额付款但是余额不足，该订单无效，删除
			Table::Delete('order', $v['id']);
		}*/
		Session::Set('error','余额不足支付');
		redirect( WEB_ROOT . '/order/index.php');
	}
	foreach($order_list as $k=>$v){
		Table::UpdateCache('order', $v['id'], array(
				'service' => 'credit',
				//'money' => 0,
				'state' => 'pay',
				//'credit' => $v['origin'],
				'pay_time' => time(),
				));
		
		$order = Table::FetchForce('order', $v['id']);
		ZTeam::BuyOne($order);
	}
	
	
	redirect( WEB_ROOT . "/order/pay.php?id={$order_id}");
}

$pay_callback = "pay_team_{$order['service']}";
if ( function_exists($pay_callback) ) {
	$payhtml = $pay_callback($total_money, $order);
	die(include template('order_pay'));
}
else if ( $order['service'] == 'credit' ) {
	die(include template('order_pay'));
} 
else {
	Session::Set('error', '无合适的支付方式或余额不足');
	redirect( WEB_ROOT. "/team.php?id={$order_id}");
}
